/**
 * Created by Ng on 2023/11/16
 */

/**
 * cookie
 * 数据大小不超过 4K
 * 设置的 cookie 过期时间之前一直有效，即使窗口或浏览器关闭
 */

/**
 * @description 设置 Cookie
 * @param {String} key
 * @param {String} value
 * @param {Number} expires 到期时间（单位天）
 * @returns {Boolean}
 */
export function setCookie(key, value, expires) {
  if (!key || !value) return
  let date = new Date()
  date = date.setDate(date.getDate() + expires)
  return document.cookie = key + '=' + value + ';expires=' + new Date(date).toUTCString()
}

/**
 * @description 获取指定的 Cookie
 * @param {String} key 
 * @returns {String | Null}
 */
export function getCookie(key) {
  if (!key) return
  // cookie 之间是用 `; ` 隔开的
  let cookies = decodeURIComponent(document.cookie)
  if (!cookies) {
    return null
  }
  let cookieList = cookies.split('; ');
  for (let index = 0; index < cookieList.length; index++) {
    let item = cookieList[index].split('=');
    if (item[0] === key) {
      return item[1]
    }
  }
  return null
}

/**
 * @description 删除指定的 Cookie
 * @param {String} key 
 * @returns {Boolean}
 */
export function removeCookie(key) {
  if (!key) return
  return document.cookie = encodeURIComponent(key) + '=;expires=' + new Date()
}
